package com.higold.cloud.ui.fragment

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.net.http.SslError
import android.os.Bundle
import android.util.Log
import android.webkit.*
import com.alibaba.fastjson.JSONObject
import com.github.lzyzsd.jsbridge.BridgeWebView
import com.higold.cloud.R
import com.higold.cloud.base.BaseFragment
import com.higold.cloud.utils.StatusBarUtil
import com.higold.cloud.utils.WVJBWebViewClient
import kotlinx.android.synthetic.main.fragment_new_home.*
import com.higold.cloud.base.BaseWebviewActivity
import com.github.lzyzsd.jsbridge.CallBackFunction
import com.github.lzyzsd.jsbridge.BridgeHandler
import com.github.lzyzsd.jsbridge.BridgeWebViewClient
import com.gyf.immersionbar.ktx.immersionBar
import kotlinx.android.synthetic.main.activity_profile_homepage.*


/**
 *    author : lxz
 *    date   : 2019/5/14 16:53
 *    desc   :首页
 */
class NewHomeFragment : BaseFragment() {

    internal var webview: BridgeWebView? = null
    private var webViewClient: MyWebViewClient? = null
    private var mTitle: String? = null
    private var mUploadMessage: ValueCallback<Uri>? = null

    companion object {
        fun getInstance(title: String): NewHomeFragment {
            val fragment = NewHomeFragment()
            val bundle = Bundle()
            fragment.arguments = bundle
            fragment.mTitle = title
            return fragment
        }
    }

    private var wcci: WebChromeClient = object : WebChromeClient() {
        // For Android 3.0+
        fun openFileChooser(uploadMsg: ValueCallback<Uri>) {
            mUploadMessage = uploadMsg
        }

        // For Android 3.0+
        fun openFileChooser(uploadMsg: ValueCallback<Uri>, acceptType: String) {
            mUploadMessage = uploadMsg
        }

        //For Android 4.1
        fun openFileChooser(uploadMsg: ValueCallback<Uri>, acceptType: String, capture: String) {
            mUploadMessage = uploadMsg
        }
    }


    override fun getLayoutId(): Int = R.layout.fragment_new_home

    @SuppressLint("SetJavaScriptEnabled")
    override fun initView() {

        tv_title.text = mTitle
        //状态栏透明和间距处理
//        activity?.let { StatusBarUtil.darkMode(it)
//            StatusBarUtil.darkMode(it, false)
//            StatusBarUtil.setPaddingSmart(it, home_toolbar)}

        webview = view!!.findViewById(R.id.bw_home) as BridgeWebView
        //webview.setVisibility(View.GONE);

        val webSettings = webview!!.getSettings()
        webSettings.allowFileAccess = true
        webSettings.javaScriptEnabled = true
        webSettings.domStorageEnabled = true //百度地图加载

        val ua = webview!!.settings.getUserAgentString()

        webSettings.userAgentString = "$ua;general"

        webview!!.webChromeClient = wcci
        webViewClient = MyWebViewClient(webview!!)
        webview!!.webViewClient = webViewClient //用定义的webviewclient
        //webview.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
        //webview.setVerticalScrollBarEnabled(false); //垂直不显示  滚动条
        webSettings.defaultTextEncodingName = "utf-8"

        webSettings.useWideViewPort = true
        webSettings.loadWithOverviewMode = true
        webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN

        webSettings.blockNetworkImage = false//解除阻止

        webSettings.blockNetworkLoads = false//

        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE

        webSettings.setAppCacheEnabled(false)//不缓存


        webview!!.loadUrl("file:////android_asset/1.0/index.html#/one")

        webview!!.registerHandler("setNavBarTitle") { data, _ ->
            val data_json = JSONObject.parseObject(data.toString())
        }

        webview!!.registerHandler("push") { data, _ ->
            //显示接收的消息

            val data_json = JSONObject.parseObject(data.toString())


            if (data_json.getString("type") == "native") {

                var activityClass: Class<*>? = null //跳到其他原生页面
                try {
                    activityClass = Class.forName(data_json.getString("target"))
                } catch (e: ClassNotFoundException) {
                    e.printStackTrace()
                }

                val intent = Intent(activity, BaseWebviewActivity::class.java)

                intent.putExtra("js_params", data_json.toString())

                if (data_json.getString("animated") == "true") {

                    //加动画

                } else {
                    //没动画
                }

                startActivity(intent)//启动Activity

            } else {

                val intent = Intent(activity, BaseWebviewActivity::class.java)

                intent.putExtra("js_params", data_json.toString())

                if (data_json.getString("animated") == "true") {

                    //加动画

                } else {
                    //没动画
                }

                startActivity(intent)//启动Activity
            }
        }

    }

    override fun lazyLoad() {

    }

    inner class MyWebViewClient(webView: BridgeWebView) : BridgeWebViewClient(webView) {

        override fun onReceivedHttpError(
                view: WebView,
                request: WebResourceRequest,
                errorResponse: WebResourceResponse
        ) {

            super.onReceivedHttpError(view, request, errorResponse)

            Log.e("onReceivedHttpError", "onReceivedHttpError进来了")

        }

        override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) {
            super.onReceivedError(view, request, error)


            Log.e("onReceivedError", "onReceivedError进来了")
        }


        //添加下面2行代码来忽略SSL验证
        override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
            handler.proceed()
        }


    }


}